const express = require('express');
//数据库
const mongoose = require('mongoose');
const bodyParser = require('body-parser');

//引入passport jwt验证使用  引入初始化配置
const passport = require('passport');

//创建app
const app = express();
//引入users
const users = require('./routes/api/users');
const profiles = require('./routes/api/profiles');

//使用bodyParser中间件
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());


//DB config
//Connect to mongodb
mongoose.connect(require('./config/keys').mongoURI)
    .then(() => console.info("数据库连接成功"))
    .catch(() => console.error("数据库连接失败"));


//初始化passport
app.use(passport.initialize());
//配置passport
require('./config/passport')(passport);


// app.get('/', (req, res) => {
//     res.send("hello world");
// });

app.all("*",function(req,res,next){
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
    res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
    next();

})

//使用中间件路由
app.use("/api/users", users);
app.use("/api/profiles", profiles);
//定义端口
const port = process.env.PORT || 5000;
//监听端口
app.listen(port, () => {
    console.info(`server is running on port ${port}`);
});

